package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.common.Consts;
import com.github.aloxc.plugin.restplus.entity.RestConfig;
import com.github.aloxc.plugin.restplus.entity.Sort;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.github.aloxc.plugin.restplus.navigator.RestServicesNavigator;
import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class SortListener extends MouseAdapter implements ActionListener {
    private Project project;
    public SortListener(Project project) {
        this.project = project;
    }

    @Override
    public void mouseClicked(MouseEvent event) {
        Component showButton = (JButton)event.getSource();
        int x = event.getX();
        int y = event.getY() + 5;
        JPopupMenu menu = new JPopupMenu();
        JMenuItem asc = new JMenuItem(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.response.sort.asc.text"));
        asc.setName(Sort.ASC.getType());
        JMenuItem desc = new JMenuItem(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.response.sort.desc.text"));
        desc.setName(Sort.DESC.getType());

        asc.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        desc.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        asc.setIcon(Consts.Icons.ASC);
        desc.setIcon(Consts.Icons.DESC);
        RestConfig config = project.getComponent(RestServicesNavigator.class).getConfig();
        menu.add(asc);
        menu.add(desc);
        asc.addActionListener(this);
        desc.addActionListener(this);
        menu.show(showButton, x, y);
        JMenuItem curItem = null;
        if (config == null) {
            curItem = asc;
        }
        Sort sort = Sort.get();
        if(sort == null){
            curItem = asc;
            sort = Sort.ASC;
            Sort.set(sort);
        }
        String showName = Sort.get().getType();
        if (asc.getName().equals(showName)) {
            curItem = asc;
        } else {
            curItem = desc;
        }
        curItem.setSelected(true);
        curItem.setIcon(Consts.Icons.CUR);
        curItem.setForeground(Consts.MAIN_COLOR);
        curItem.setBackground(Consts.COOKIE_BACKGROUND_COLOR);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        String sortType = ((JMenuItem) event.getSource()).getName();
        Sort.set(Sort.getByType(sortType));

        new RefreshListener(project).doRefreshProject();
    }
}